using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CanonBehavior : MonoBehaviour 
{
	public int Delay;
	public Vector3 CanonballSpeed;
	public GameObject Canonball;
	public int CanonballCount;
	
	private float PreviousLaunchTime;
	private List<GameObject> CanonballsList;
	private Vector3 CanonBallOffset = new Vector3(-5, 5, -6);
	
	// Use this for initialization
	void Start () 
	{
		PreviousLaunchTime = Time.time;
		CanonballsList = new List<GameObject>();
		
		//create the canonball
		for(int i = 0; i < CanonballCount; ++i)
		{
			GameObject NewCanonball = (GameObject)Instantiate(Canonball);
			NewCanonball.SetActive(false);
			CanonballsList.Add(NewCanonball);
		}
	}
	
	// Update is called once per frame
	void Update () 
	{
		if(Time.time >= PreviousLaunchTime + Delay)
		{
			//spawn
			//Debug.Log("Spawn");
			launch();
			PreviousLaunchTime = Time.time;
		}
	}
	
	private void launch()
	{
		foreach(GameObject go in CanonballsList)
		{
			if(go.activeInHierarchy)
				continue;
			
			CanonballBehavior cCanonball = go.GetComponent<CanonballBehavior>();
			cCanonball.Speed = CanonballSpeed;
			cCanonball.transform.position = transform.position + CanonBallOffset;
			go.SetActive(true);
				
		}		
	}
}
